package io.gitee.mingbaobaba.security.starter.request;

import io.gitee.mingbaobaba.security.core.constants.ErrorCodeConstant;
import io.gitee.mingbaobaba.security.core.exception.SecurityBaseException;
import io.gitee.mingbaobaba.security.core.request.SecurityRequest;
import io.gitee.mingbaobaba.security.starter.utils.ServletUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>request实现</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/8/29 9:34
 */
public class SecurityHttpServletRequest implements SecurityRequest {

    @Override
    public Object target() {
        return ServletUtil.getRequest();
    }

    @Override
    public String getHeader(String name) {
        return ((HttpServletRequest) target()).getHeader(name);
    }

    @Override
    public String getParameter(String name) {
        return ((HttpServletRequest) target()).getParameter(name);
    }

    @Override
    public String getParameterNonNull(String name) {
        String value = getParameter(name);
        if (StringUtils.isBlank(value)) {
            throw new SecurityBaseException(ErrorCodeConstant.CODE_INVALID_PARAMS,
                    String.format("获取参数名为%s的值为空", name));
        }
        return value;
    }

    @Override
    public SecurityRequest setAttribute(String name, Object value) {
        ((HttpServletRequest) target()).setAttribute(name, value);
        return this;
    }

    @Override
    public Object getAttribute(String name) {
        return ((HttpServletRequest) target()).getAttribute(name);
    }

    @Override
    public void removeAttribute(String name) {
         ((HttpServletRequest) target()).removeAttribute(name);
    }

    @Override
    public String getCookie(String name) {
        Cookie[] cookies = ((HttpServletRequest) target()).getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    @Override
    public String getRequestURI() {
        return ((HttpServletRequest) target()).getRequestURI();
    }

    @Override
    public String getRequestURL() {
        return ((HttpServletRequest) target()).getRequestURL().toString();
    }

    @Override
    public String getServletPath() {
        return ((HttpServletRequest) target()).getServletPath();
    }

    @Override
    public String getContextPath() {
        return ((HttpServletRequest) target()).getContextPath();
    }
}
